package com.nantian.common.util;

import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>ClassName: DateUtils</p >
 * <p>Description: 日期工具类 </p >
 * <p>Copyright: Copyright©2014</p >
 * <p>Company: 广州南天电脑系统有限公司</p >
 * <p>Date: 2021-02-07</p >
 *
 * @author 刘晓辉
 * @version 1.0
 */
public class DateUtils {

    /**
     * 解析日期
     * @param dateStr 日期字符串
     * @param pattern 日期格式
     * @return Date时间
     */
    public static Date parse(String dateStr, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 解析日期
     * @param dateStr 日期字符串
     * @param pattern 日期格式
     * @return 时间戳
     */
    public static Long parseTimestamp(String dateStr, String pattern) {
        Date date = parse(dateStr, pattern);
        return date.getTime();
    }

    /**
     * 格式化日期
     * @param date date日期
     * @param pattern 日期格式
     * @return 日期字符串
     */
    public static String format(Date date, String pattern) {
        return DateFormatUtils.format(date, pattern);
    }


    public static Date addYears(Date date, int amount) {
        return add(date, 1, amount);
    }

    public static Date addMonths(Date date, int amount) {
        return add(date, 2, amount);
    }

    public static Date addWeeks(Date date, int amount) {
        return add(date, 3, amount);
    }

    public static Date addDays(Date date, int amount) {
        return add(date, 5, amount);
    }

    public static Date addHours(Date date, int amount) {
        return add(date, 11, amount);
    }

    public static Date addMinutes(Date date, int amount) {
        return add(date, 12, amount);
    }

    public static Date addSeconds(Date date, int amount) {
        return add(date, 13, amount);
    }

    public static Date addMilliseconds(Date date, int amount) {
        return add(date, 14, amount);
    }
    private static Date add(Date date, int calendarField, int amount) {
        validateDateNotNull(date);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

    private static void validateDateNotNull(Date date) {
        Validate.isTrue(date != null, "The date must not be null", new Object[0]);
    }
}
